<template>
  <div>
    <div v-if="!data" slot="empty" class="emptyBg">
      <el-empty :image-size="200"></el-empty>
    </div>
    <MyEcharts v-else :option="option" />
  </div>
</template>
<script>
import Bus from "@/utils/bus.js";
export default {
  components: {
    MyEcharts: () => import("@/components/myEcharts/index.vue"),
  },
  data() {
    return {
      option: null,
      firstData: [],
      option: null,
      curFirstTitle: "",
    };
  },
  props: ["data"],
  watch: {
    data() {
      this.init();
    },
  },
  mounted() {
    this.init();
    Bus.$on("changeIdx", (v) => {
      this.init(v);
    });
  },
  beforeDestroy() {
    Bus.$off("changeIdx");
  },
  methods: {
    init(curIdx) {
      if (!this.data) return;
      curIdx = curIdx || 0;
      let arr = [];
      this.firstData = this.uniqueById(this.data.map((v) => v.level1));
      let curId = this.firstData[curIdx].id;
      this.curFirstTitle = this.firstData[curIdx].name;
      let secondData = this.data.filter((v) => v.level1.id == curId);
      let secondDataMap = this.uniqueById(secondData.map((v) => v.level2));
      secondDataMap.forEach((v) => {
        let n = 0;
        secondData.forEach((m) => {
          if (v.id == m.level2.id) {
            n += parseInt(m.num);
          }
        });
        arr.push(n);
      });
      this.initEcharts(secondDataMap, arr);
    },
    initEcharts(data, arr) {
      // 柱状图
      this.option = {
        tooltip: {},
        xAxis: {
          type: "category",
          data: data.map((v) => v.name),
        },
        yAxis: {},
        textStyle: {
          fontSize: "14",
          color: "#1cc5c9",
        },
        series: [
          {
            type: "bar",
            name: this.curFirstTitle,
            data: arr,
            barMinHeight: 2,
            itemStyle: {
              color: {
                type: "linear",
                x: 0, //右
                y: 0, //下
                x2: 0, //左
                y2: 1, //上
                colorStops: [
                  {
                    offset: 0,
                    color: "#65dee7", // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "#1882f2", // 100% 处的颜色
                  },
                ],
              },
            },
          },
        ],
      };
    },
  },
};
</script>
<style scoped lang="scss">
</style>